//
//  AFNetHandle.m
//  热点
//
//  Created by dllo on 15/9/22.
//  Copyright (c) 2015年 荣伟峰. All rights reserved.
//

#import "AFNetHandle.h"

@implementation AFNetHandle

+(void)GETWithURL:(NSString *)url body:(NSDictionary *)body httpHead:(NSDictionary *)head responseStyle:(responseStyle)style success:(void (^)(id result))success fail:(void (^)(NSError *error))fail {
    
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    
    //本地缓存设置，沙盒路径设置
    NSArray *path =NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    
    NSString *pathString =path.lastObject;
    
    NSString *pathLast =[NSString stringWithFormat:@"/Caches/com.hackemist.SDWebImageCache.default/%lu.text", (unsigned long)[url hash]];
    
    
    //创建字符串文件存储路径
    NSString *PathName =[pathString stringByAppendingString:pathLast];
//    NSLog(@"%@", PathName);
    //第一次进入判断有没有文件夹，如果没有就创建一个
    NSString * textPath = [pathString stringByAppendingFormat:@"/Caches/com.hackemist.SDWebImageCache.default"];
    if (![[NSFileManager defaultManager]fileExistsAtPath:textPath]) {
        
        [[NSFileManager defaultManager]createDirectoryAtPath:textPath withIntermediateDirectories:YES attributes:nil error:nil];
    }

    //设BOOL值 判断解析后的数据是数组还是字典
    __block  BOOL isClass = NO;

    
    // WiFi边上的 菊花
    UIApplication *application = [UIApplication sharedApplication];
    application.networkActivityIndicatorVisible = YES;
    
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    /* 1.创建一个网络请求管理者 */
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    /* 2.添加请求头 */
    if (head) {
        for (NSString *key in head) {
            [manager.requestSerializer setValue:head[key] forHTTPHeaderField:key];
        }
    }
    /* 3.判断返回值类型 */
    switch (style) {
        case DATA: {
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
        }
        case JSON: {
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
        }
        case XML: {
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        }
        default:
            break;
    }
    /* 4.设置请求接受的数据类型 */
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil]];
    /* 5.get请求 */
    
    [manager GET:url parameters:body success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        [netWorkManager stopMonitoring];
        
        if ([responseObject isKindOfClass:[NSArray class]]) {
            isClass = YES;
        } else{
            isClass = NO;
        }
        [responseObject writeToFile:PathName atomically:YES];
        
        if (success) {
            success(responseObject);
        }
        application.networkActivityIndicatorVisible = NO;
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
        NSString * cachePath = PathName;
        
        if ([[NSFileManager defaultManager] fileExistsAtPath:cachePath]) {
            //从本地读缓存文件
            id responseObject = nil;
            if (isClass) {
                responseObject = [NSMutableArray arrayWithContentsOfFile:cachePath];
            }else{
                
                responseObject = [NSMutableDictionary dictionaryWithContentsOfFile:cachePath];
            }
            
            success(responseObject);
            
        } else {
            fail(error);
            
        }
        application.networkActivityIndicatorVisible = NO;
    }];
    
}

@end
